package com.megaclient.activity;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.megaclient.R;

public class MegaClientActivity extends Activity {
	private EditText hostEditText;
	private EditText portEditText;
	private TextView messageTextView;
	private Button connectButton;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		connectButton = (Button) findViewById(R.id.connectButton);
		messageTextView = (TextView) findViewById(R.id.messageTextView);
		hostEditText = (EditText) findViewById(R.id.hostEditText);
		portEditText = (EditText) findViewById(R.id.portEditText);

		connectButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(final View v) {
				final String host = hostEditText.getText().toString();
				final int port = Integer.parseInt(portEditText.getText().toString());
				try {
					// Try reaching the host.
					new Socket(host, port);

					// If succeed, open control activity.
					final Intent intent = new Intent(MegaClientActivity.this, ControlActivity.class);
					intent.putExtra("host", hostEditText.getText().toString());
					intent.putExtra("port", Integer.parseInt(portEditText.getText().toString()));
					startActivity(intent);
				} catch (final UnknownHostException e) {
					Log.d("Something", e.getMessage());
					messageTextView.setText("Unknown host");
				} catch (final IOException e) {
					Log.d("Something", e.getMessage());
					messageTextView.setText("Unknown error");
				}
			}
		});
	}
}